#include "processmanager.h"
#include <fstream>
#include <sstream>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <pwd.h>
#include <signal.h>
#include <chrono>
#include <map>

ProcessManager::ProcessManager() {
    // 构造函数
}

ProcessManager::~ProcessManager() {
    // 析构函数
}

std::vector<ProcessInfo> ProcessManager::get_all_processes() {
    return filter_processes("all");
}

std::vector<ProcessInfo> ProcessManager::get_user_processes() {
    return filter_processes("user");
}

std::vector<ProcessInfo> ProcessManager::get_system_processes() {
    return filter_processes("system");
}

std::vector<ProcessInfo> ProcessManager::get_service_processes() {
    return filter_processes("services");
}

std::vector<ProcessInfo> ProcessManager::get_processes() {
    return get_all_processes();
}

void ProcessManager::refresh_processes(const std::string& filter_type) {
    // 刷新进程列表
    m_processes = filter_processes(filter_type);
}

bool ProcessManager::terminate_process(int pid) {
    return kill_process(pid);
}

bool ProcessManager::kill_process(int pid) {
    return (kill(pid, SIGTERM) == 0);
}

bool ProcessManager::kill_process_tree(int pid) {
    // 简单实现，只终止单个进程
    return kill_process(pid);
}

std::vector<ProcessInfo> ProcessManager::filter_processes(const std::string& filter_type) {
    std::vector<ProcessInfo> processes;
    
    // 记录当前时间
    auto now = std::chrono::steady_clock::now();
    auto time_since_last_update = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_last_update).count();
    bool first_update = (time_since_last_update > 10000); // 如果超过10秒认为是第一次更新
    m_last_update = now;
    
    DIR* dir = opendir("/proc");
    if (!dir) {
        return processes;
    }
    
    struct dirent* entry;
    while ((entry = readdir(dir)) != nullptr) {
        // 检查是否为进程目录（数字命名）
        if (entry->d_type == DT_DIR && std::isdigit(entry->d_name[0])) {
            int pid = std::stoi(entry->d_name);
            
            ProcessInfo process;
            process.pid = pid;
            
            // 初始化默认值
            process.cpu_percent = 0.0;
            process.memory_percent = 0.0;
            process.memory_mb = 0.0;
            process.time = "00:00:00";
            process.running_time = "00:00:00";
            process.priority = 0;
            process.disk_read_kb = 0.0;
            process.disk_write_kb = 0.0;
            process.network_recv_kb = 0.0;
            process.network_send_kb = 0.0;
            
            // 获取上一次采样数据
            ProcessSample last_sample = {};
            bool has_last_sample = m_process_samples.find(pid) != m_process_samples.end();
            if (has_last_sample && !first_update) {
                last_sample = m_process_samples[pid];
            }
            
            // 读取进程信息
            std::string stat_path = "/proc/" + std::string(entry->d_name) + "/stat";
            std::ifstream stat_file(stat_path);
            if (stat_file.is_open()) {
                std::string line;
                std::getline(stat_file, line);
                std::istringstream iss(line);
                
                std::string pid_str, comm, state;
                iss >> process.pid >> comm >> state;
                
                // 处理进程名
                process.name = comm;
                if (!process.name.empty() && process.name.front() == '(' && process.name.back() == ')') {
                    process.name = process.name.substr(1, process.name.length() - 2);
                }
                
                // 设置状态
                switch (state[0]) {
                    case 'R': process.status = "运行"; break;
                    case 'S': process.status = "睡眠"; break;
                    case 'D': process.status = "不可中断睡眠"; break;
                    case 'T': process.status = "停止"; break;
                    case 'Z': process.status = "僵尸"; break;
                    case 'X': process.status = "死亡"; break;
                    default: process.status = "未知"; break;
                }
                
                // 跳过一些字段直到获取到utime和stime
                for (int i = 0; i < 11; i++) {
                    std::string dummy;
                    iss >> dummy;
                }
                
                unsigned long utime, stime, starttime;
                iss >> utime >> stime;
                
                // 跳过一些字段直到获取到starttime
                for (int i = 0; i < 13; i++) {
                    std::string dummy;
                    iss >> dummy;
                }
                iss >> starttime;
                
                // 计算CPU使用率
                if (has_last_sample && !first_update && time_since_last_update > 0) {
                    unsigned long total_time = (utime - last_sample.utime) + (stime - last_sample.stime);
                    double cpu_usage = (double)total_time / sysconf(_SC_CLK_TCK) / (time_since_last_update / 1000.0) * 100.0;
                    process.cpu_percent = cpu_usage;
                }
                
                // 计算运行时间
                long uptime = 0;
                std::ifstream uptime_file("/proc/uptime");
                if (uptime_file.is_open()) {
                    std::string uptime_line;
                    std::getline(uptime_file, uptime_line);
                    std::istringstream uptime_iss(uptime_line);
                    double uptime_seconds;
                    uptime_iss >> uptime_seconds;
                    uptime = (long)uptime_seconds;
                    uptime_file.close();
                }
                
                // 计算进程启动时间
                long ticks_per_second = sysconf(_SC_CLK_TCK);
                long process_uptime = uptime - (starttime / ticks_per_second);
                
                // 格式化运行时间
                int hours = process_uptime / 3600;
                int minutes = (process_uptime % 3600) / 60;
                int seconds = process_uptime % 60;
                
                std::stringstream time_ss;
                time_ss.fill('0');
                time_ss.width(2);
                time_ss << hours << ":";
                time_ss.fill('0');
                time_ss.width(2);
                time_ss << minutes << ":";
                time_ss.fill('0');
                time_ss.width(2);
                time_ss << seconds;
                process.running_time = time_ss.str();
                
                // 保存当前采样
                ProcessSample current_sample;
                current_sample.utime = utime;
                current_sample.stime = stime;
                current_sample.timestamp = now;
                
                // 读取IO数据
                std::string io_path = "/proc/" + std::string(entry->d_name) + "/io";
                std::ifstream io_file(io_path);
                if (io_file.is_open()) {
                    std::string io_line;
                    while (std::getline(io_file, io_line)) {
                        if (io_line.substr(0, 11) == "read_bytes:") {
                            std::istringstream read_iss(io_line.substr(12));
                            read_iss >> current_sample.read_bytes;
                        } else if (io_line.substr(0, 12) == "write_bytes:") {
                            std::istringstream write_iss(io_line.substr(13));
                            write_iss >> current_sample.write_bytes;
                        }
                    }
                    
                    // 计算IO速率
                    if (has_last_sample && !first_update && time_since_last_update > 0) {
                        unsigned long long read_diff = current_sample.read_bytes - last_sample.read_bytes;
                        unsigned long long write_diff = current_sample.write_bytes - last_sample.write_bytes;
                        
                        process.disk_read_kb = (double)read_diff / 1024.0 / (time_since_last_update / 1000.0);
                        process.disk_write_kb = (double)write_diff / 1024.0 / (time_since_last_update / 1000.0);
                    }
                }
                
                // 保存采样数据
                m_process_samples[pid] = current_sample;
            }
            
            // 读取命令行
            std::string cmdline_path = "/proc/" + std::string(entry->d_name) + "/cmdline";
            std::ifstream cmdline_file(cmdline_path);
            if (cmdline_file.is_open()) {
                std::getline(cmdline_file, process.command_line);
                // 替换null字符为空格
                for (char& c : process.command_line) {
                    if (c == '\0') c = ' ';
                }
                if (process.command_line.empty()) {
                    process.command_line = process.name;
                }
            } else {
                process.command_line = process.name;
            }
            
            // 获取用户信息和内存使用情况
            std::string status_path = "/proc/" + std::string(entry->d_name) + "/status";
            std::ifstream status_file(status_path);
            if (status_file.is_open()) {
                std::string line;
                while (std::getline(status_file, line)) {
                    if (line.substr(0, 5) == "Uid:\t") {
                        std::istringstream uid_iss(line.substr(5));
                        int uid;
                        uid_iss >> uid;
                        struct passwd* pwd = getpwuid(uid);
                        if (pwd) {
                            process.user = pwd->pw_name;
                        } else {
                            process.user = std::to_string(uid);
                        }
                    } else if (line.substr(0, 6) == "VmRSS:") {
                        // 获取内存使用情况 (kB)
                        std::istringstream vmrss_iss(line.substr(6));
                        unsigned long vmrss_kb;
                        vmrss_iss >> vmrss_kb;
                        process.memory_mb = (double)vmrss_kb / 1024.0;
                    }
                }
            }
            
            // 获取内存使用百分比
            // 获取系统总内存
            std::ifstream meminfo_file("/proc/meminfo");
            if (meminfo_file.is_open()) {
                std::string line;
                long long mem_total = 0;
                while (std::getline(meminfo_file, line)) {
                    if (line.substr(0, 8) == "MemTotal:") {
                        std::istringstream iss(line.substr(9));
                        iss >> mem_total;  // KB
                        break;
                    }
                }
                
                if (mem_total > 0) {
                    process.memory_percent = (process.memory_mb * 1024.0) / mem_total * 100.0;
                }
            }
            
            // 获取网络信息 (从/proc/net/dev中解析，但这比较复杂，简化处理)
            // 这里只是示例，实际需要更复杂的处理来获取每个进程的网络使用情况
            // 为了简化，我们暂时使用默认值
            
            // 根据过滤器类型添加进程
            bool add_process = false;
            if (filter_type == "all") {
                add_process = true;
            } else if (filter_type == "user" && process.user != "root") {
                add_process = true;
            } else if (filter_type == "system" && process.user == "root") {
                add_process = true;
            } else if (filter_type == "services") {
                // 简化处理，将系统进程视为服务
                add_process = (process.user == "root");
            }
            
            if (add_process) {
                processes.push_back(process);
            }
        }
    }
    
    closedir(dir);
    return processes;
}